import cv2

def capture_photo():
    cap = cv2.VideoCapture(0)
    
    if not cap.isOpened():
        print("无法打开摄像头")
        return

    # 创建固定大小的窗口
    cv2.namedWindow("Camera", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Camera", 640, 480)  # 设置窗口大小为640x480
    
    photo_count = 0
    
    while True:
        # 读取摄像头画面
        ret, frame = cap.read()
        if not ret:
            print("无法获取图像")
            break
            
        # 显示画面
        cv2.imshow("Camera", frame)
        
        # 检测按键
        key = cv2.waitKey(1) & 0xFF
        
        # 按空格键拍照
        if key == ord(' '):
            photo_count += 1
            filename = f'photo_{photo_count}.jpg'
            cv2.imwrite(filename, frame)
            print(f"照片已保存为 {filename}")
        
        # 按q键退出
        elif key == ord('q'):
            break
    
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    capture_photo()